package com.lovi.service;

import com.lovi.common.MessageType;
import com.lovi.common.Message;
import com.lovi.common.User;
import com.lovi.common.UsersMap;
import com.lovi.thread_.ManageServerConnectClientThread;
import com.lovi.thread_.ServerConnectClientThread;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.concurrent.ConcurrentHashMap;

public class QQServerServiceImpl {
    private ManageServerConnectClientThread ConnectThreadMap = new ManageServerConnectClientThread();

    private boolean checkUser (User user){
        String userId = user.getUserId();
        String password = user.getPassword();
        //先判断有没有key
        if(UsersMap.usersMap.get(userId)==null){
            return false;
        }
        //判断用户名密码时是否正确
        if(!UsersMap.usersMap.get(userId).equals(password)){
            return false;
        }
        return true;
    }
    /**
     * 接收客户端发送过来的用户信息
     * 返回登录结果
     */
    public void login() throws IOException, ClassNotFoundException {
        //1.开启9999的端口监听
        ServerSocket serverSocket = new ServerSocket(9999);
        System.out.println("服务器启动了...");
        //2.接收用户的用户信息
        //  考虑到会有多个用户连接，因此循环读取
        Socket socket = null;
        while (true) {
            socket = serverSocket.accept();
            ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
            User user = (User) ois.readObject();
            ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
            //默认100,123456才能登录成功
            Message message = new Message();
            if (checkUser(user)) {
                //登录成功
                System.out.println("用户"+user.getUserId()+"登录成功");
                message.setMestype(MessageType.LOGIN_SUCCESS);
                oos.writeObject(message);
                //建立消息通道（也是同理，建立线程）
                ServerConnectClientThread thread = new ServerConnectClientThread(socket, user.getUserId());
                thread.start();
                ConnectThreadMap.addServerConnectClientThread(user.getUserId(), thread);

            } else {
                message.setMestype(MessageType.LOGIN_FAIL);
                oos.writeObject(message);
                //登录失败,关闭socket
                socket.close();
            }
        }
    }
}
